from flask import Request
from server import sio, JWT_SECRET
from utils.jwt_util import verify_jwt

def check_token(token):
    payload = verify_jwt(token, secret=JWT_SECRET)
    if payload:
          return payload.get('payload')
    else:
        return None


@sio.on('connect')
def connect(sid, envron):
    request = Request(envron)
    token = request.args.get('token')
    # 解析token
    user_id = check_token(token)
    # 一旦用户连接到IM服务器, 就让他进入其user_id对应的房间 (一个人对应一个房间)
    sio.enter_room(sid, room=user_id)
    print("进入了房间:%s" % user_id)


@sio.on('disconnect')
def disconnect(sid):
    # 断开连接后退出房间
    rooms = sio.rooms(sid)
    for room in rooms:
        sio.leave_room(sid, room=room)
